import { getToken } from '@/utils/storage';

const initialState = {
  profile: {} as Person,
  user: {} as UserInfo,
  auth: getToken(),
};

// 给action传来的参数定义类型
export type Auth = {
  token: string;
  refresh_token: string;
};

// 定义action类型
export type UserAction =
  | { type: 'user/getToken'; payload: Auth }
  | { type: 'user/userInfo'; payload: UserInfo }
  | { type: 'user/person'; payload: Person }
  | { type: 'user/uploadPhoto'; payload: Partial<Person> }
  | { type: 'user/uploadGender'; payload: Partial<Person> }
  | { type: 'user/uploadUserName'; payload: Partial<Person> }
  | { type: 'user/uploadIntro'; payload: Partial<Person> }
  | { type: 'user/uploadBirthDay'; payload: Partial<Person> };

// 定义用户自己信息的返回值类型
export type UserInfo = {
  art_count: number;
  fans_count: number;
  follow_count: number;
  id: string;
  intro: string;
  like_count: number;
  name: string;
  photo: string;
};

// 定义用户个人资料
export type Person = {
  id: string;
  photo: string;
  name: string;
  mobile: string;
  gender: number;
  birthday: string;
  intro: string;
};
// 登录获取token
export default function userReducer(
  state = initialState,
  action: UserAction
): typeof initialState {
  switch (action.type) {
    // 登录获取token
    case 'user/getToken':
      return {
        ...state,
        auth: action.payload,
      };

    // 获取用户信息
    case 'user/userInfo':
      return {
        ...state,
        user: action.payload,
      };

    // 获取用户个人资料
    case 'user/person':
      return {
        ...state,
        profile: action.payload,
      };

    // 修改个人资料的头像
    case 'user/uploadPhoto':
      return {
        ...state,
        profile: { ...state.profile, ...action.payload },
      };

    // 编辑用户性别
    case 'user/uploadGender':
      return {
        ...state,
        profile: { ...state.profile, ...action.payload },
      };

    // 编辑用户昵称
    case 'user/uploadUserName':
      return {
        ...state,
        profile: { ...state.profile, ...action.payload },
      };

    // 编辑用户简介
    case 'user/uploadIntro':
      return {
        ...state,
        profile: { ...state.profile, ...action.payload },
      };

    // 编辑用户简介
    case 'user/uploadBirthDay':
      return {
        ...state,
        profile: { ...state.profile, ...action.payload },
      };

    default:
      return state;
  }
}
